package com.springboot_nanhua4.controllers;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import com.springboot_nanhua4.model.Student;
import com.springboot_nanhua4.service.StudentService;
import com.springboot_nanhua4.controllers.ResponseResult;

@RestController
@RequestMapping("/student")
public class StudentController {

    @Autowired
    private StudentService studentService;

    // 保留查询方法（无需修改）
    @GetMapping("/find/{id}")
    public ResponseEntity<ResponseResult> findById(@PathVariable("id") Integer id) {
        Student s = studentService.find(id);
        if (s == null) {
            return ResponseEntity.ok(ResponseResult.error("查无此id的学生"));
        }
        return ResponseEntity.ok(ResponseResult.ok().setData(s));
    }

    // 修正点1：添加consumes属性，支持文件上传的multipart/form-data格式
    // 修正点2：将@RequestBody改为@ModelAttribute，接收表单（含文件）数据
    @PostMapping(value = "/add", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public ResponseEntity<ResponseResult> add(
            @ModelAttribute Student s,
            // 若前端单独传递文件参数，需补充此参数（与前端file参数名一致）
            @RequestParam(value = "photoFile", required = false) MultipartFile photoFile
    ) {
        // 关联文件到Student对象（若Student类中已定义photoFile属性，可省略此步）
        s.setPhotofile(photoFile);
        System.out.println(s);

        try {
            s = studentService.add(s);
        } catch (RuntimeException e) {
            // 捕获Service层抛出的异常（如文件上传失败），返回错误信息
            return ResponseEntity.ok(ResponseResult.error(e.getMessage()));
        }

        // 移除冗余的boolean判断，直接基于Service返回结果响应
        return ResponseEntity.ok(ResponseResult.ok().setData(s));
    }

    // 其他方法...
}